package com.taotao.rest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.rest.dao.JedisClient;
import com.taotao.rest.pojo.Item;
import com.taotao.utils.JsonUtils;


@Service
public class ItemServiceImpl implements ItemService {
	@Autowired
	private TbItemMapper tbItemMapper;
	@Autowired
	private TbItemDescMapper itemDescMapper;
	
	
	@Autowired
	private JedisClient jedisClient;
	@Value("${SEARCH_ITEM_BASE_REDIS_KEY}")
	private String SEARCH_ITEM_BASE_REDIS_KEY;
	
	@Value("${SEARCH_ITEM_DESC_REDIS_KEY}")
	private String SEARCH_ITEM_DESC_REDIS_KEY;
	@Override
	public Item getItemBaseInfo(long id) {
		
		try {
			String hget = jedisClient.get(SEARCH_ITEM_BASE_REDIS_KEY+":"+id);
			if (hget != null) {
				Item jsonToPojo = JsonUtils.jsonToPojo(hget, Item.class);
				return jsonToPojo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
		TbItem result = tbItemMapper.selectByPrimaryKey(id);
		Item item = new Item();
		item.setId(result.getId()+"");
		item.setTitle(result.getTitle());
		item.setImage(result.getImage());
		item.setPrice(result.getPrice());
		item.setSellPoint(result.getSellPoint());
		
		try {
			jedisClient.set(SEARCH_ITEM_BASE_REDIS_KEY+":"+id, JsonUtils.objectToJson(item));
			jedisClient.expire(SEARCH_ITEM_BASE_REDIS_KEY+":"+id, 60*60*24);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return item;
	}
	@Override
	public Item getItemDesc(long id) {
		
		try {
			String string = jedisClient.get(SEARCH_ITEM_DESC_REDIS_KEY+":"+id);
			if (string != null) {
				Item jsonToPojo = JsonUtils.jsonToPojo(string, Item.class);
				return jsonToPojo;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		TbItemDesc selectByPrimaryKey = itemDescMapper.selectByPrimaryKey(id);
		Item item = new Item();
		item.setDesc(selectByPrimaryKey.getItemDesc());
		
		
		try {
			jedisClient.set(SEARCH_ITEM_DESC_REDIS_KEY+":"+id, JsonUtils.objectToJson(item));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return item;
	}
	

}
